//
//  OutAccountViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/17.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "OutAccountViewController.h"
#import "CandLTableViewCell.h"
#import "CandLModel.h"
#import "GetRegisterInforModel.h"
#import "AddAcountViewController.h"
#import "LookInforViewController.h"
#import "OutAcountDetialViewController.h"
#import "SupplierOrderViewController.h"
#import "SupplierViewController.h"
@interface OutAccountViewController ()

@property(nonatomic,copy)NSString*SearchKeyWord;

@end

@implementation OutAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"CandLTableViewCell" bundle:nil] forCellReuseIdentifier:@"CandLcell"];
    
     [self.homeTableView.mj_header beginRefreshing];//进来就加载
    
    [self addNavigationItemWithImageNames:@[@"返回白色"] Titles:@[@"返回"] isLeft:YES target:self action:@selector(backBtnClicked) tags:nil];
}
- (void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CandLData *data=self.dataArr[indexPath.row];
    
    CandLTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CandLcell" forIndexPath:indexPath];
    
    cell.isClick=self.isEdit;
    
    cell.deleStatue=self.deleStatue;//是否编辑状态
    
    cell.OutModel=data;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        
        CandLData *data=self.dataArr[indexPath.row];
        
        if (self.deleStatue) {
            
            data.Select=!data.Select;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
            
        }else{
            
            [self outShop:data.orderId SupplierId:data.supplierId IsEdit:YES];
            
//            GetRegisterInforModel *model=[GetRegisterInforModel new];
//
//            SupplierOrderViewController *Patro=[SupplierOrderViewController new];
//            OrderReqModel *list=[OrderReqModel new];
//            list.pageOn = YES;
//            list.pageSize = 50;
//            list.currentPage = 1;
//            list.shopId = [NSString stringWithFormat:@"%zd",[LoginStatuesModel shopId]];
//            list.orderId = [NSString stringWithFormat:@"%ld",data.orderId];
//
//            Patro.requrl = @"index.php/FoodCheckApi/ledgerOutNewAddInfo.json";
//            Patro.postUrl = @"index.php/FoodCheckApi/ledgerOutNewAdd.json";
//            Patro.supplierId = data.supplierId;
//            Patro.ishidenSearch = NO;
//            Patro.Reqmodel = list;
//            Patro.isEdit= NO;
//            Patro.isdeleMore=NO;
//            Patro.isGroupStyle=YES;
//            Patro.searchName=@"请输入商品名称";
//            Patro.title= @"新增订货";
//            [self.navigationController pushViewController:Patro animated:YES];
            
//            GetRegisterInforModel *model=[GetRegisterInforModel new];
//
//            model.token=[LoginStatuesModel getUserToken];
//
//            model.orderId=[NSString stringWithFormat:@"%ld",data.orderId];
//
//            model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
//
//            AddAcountViewController *EditPeople=[AddAcountViewController new];
//
//            EditPeople.requrl=@"/index.php/FoodCheckApi/ledgerOutAddInfo.json";
//
//            EditPeople.Reqmodel=model;
//
//            EditPeople.postUrl=@"/index.php/FoodCheckApi/ledgerOutAdd.json";
//
//            EditPeople.title=@"编辑出货台账";
//
//            EditPeople.BtnStr=@"保存";
//
//            EditPeople.OptionSussStr=@"保存成功";
//
//            EditPeople.block=^()
//            {
//
//                [self.homeTableView.mj_header beginRefreshing];
//            };
//
//            [self.navigationController pushViewController:EditPeople animated:YES];
        }
        
    }else{
        
        CandLData *data=self.dataArr[indexPath.row];
        
        OutAcountDetialViewController *Infor=[OutAcountDetialViewController new];
        
//        Infor.reqUrl=@"/index.php/FoodCheckApi/ledgerOutDetail.json";
        
        Infor.reqUrl=@"/index.php/FoodCheckApi/ledgerOutNewDetail.json";
        
        Infor.params=@{@"orderId":[NSString stringWithFormat:@"%ld",data.orderId]};
        
        Infor.title=@"出货台账详情";
        
        [self.navigationController pushViewController:Infor animated:YES];
        
        
    }
    
    
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        return YES;
    }
    
    return NO;
    
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        CandLData *data=self.dataArr[indexPath.row];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.orderId]];
        
        [self DelPeople:arr];
        
    }
    
}


-(void)DelPeople:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/ledgerOutDel.json" andrequestTime:5 andParams:@{@"orderIds":params} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:@"删除失败"];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}

#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:OutAcountType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:OutAcountType andIsLookSelf:isSelf];
    
    Choose.SearchPlace=self.searchName;
    
     Choose.KeyWord=self.SearchKeyWord;
    
     Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.SearchKeyWord=keyword;
        
        self.Reqmodel.params=paras;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for ( CandLData *data in self.dataArr) {
            
            data.Select=NO;
            
        }
        
        [self ChangeStatues];
        
    }
    
    [self.homeTableView reloadData];
}

-(void)SeletAll
{
    
    for ( CandLData *data in self.dataArr) {
        
        data.Select=YES;
        
    }
    
    [self ChangeStatues];
    
    [self.homeTableView reloadData];
}//全选

-(void)CanseletAll{
    
    for ( CandLData *data in self.dataArr) {
        
        data.Select=NO;
        
    }
    
    [self ChangeStatues];
    
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for ( CandLData *data in self.dataArr) {
        
        if (data.Select) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.orderId]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPeople:arr];
    
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (CandLData *data in self.dataArr) {
        
        if (data.Select) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    //新增商品
    [self outShop:0 SupplierId:0 IsEdit:false];
    
//    //新增商品
//    GetRegisterInforModel *model=[GetRegisterInforModel new];
//
//    model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
//
//    model.token=[LoginStatuesModel getUserToken];
//
//    AddAcountViewController *addPeople=[AddAcountViewController new];
//
//    addPeople.requrl=@"/index.php/FoodCheckApi/ledgerOutAddInfo.json";
//
//    addPeople.Reqmodel=model;
//
//    addPeople.postUrl=@"/index.php/FoodCheckApi/ledgerOutAdd.json";
//
//    addPeople.title=@"新增出货台账";
//
//    addPeople.BtnStr=@"新增";
//
//    addPeople.OptionSussStr=@"新增成功";
//
//    addPeople.block=^()
//    {
//
//        [self.homeTableView.mj_header beginRefreshing];
//    };
//
//    [self.navigationController pushViewController:addPeople animated:YES];
    
    
}
#pragma mark 出货商品
- (void)outShop:(NSInteger)orderId SupplierId:(NSInteger)supplierId IsEdit:(BOOL)isEdit
{
    SupplierOrderViewController *Patro=[SupplierOrderViewController new];
    OrderReqModel *list=[OrderReqModel new];
    list.pageOn = YES;
    list.pageSize = 50;
    list.currentPage = 1;
    list.shopId = [NSString stringWithFormat:@"%zd",[LoginStatuesModel shopId]];
    list.orderId = [NSString stringWithFormat:@"%ld",orderId];
    
    Patro.requrl = @"index.php/FoodCheckApi/ledgerOutNewAddInfo.json";
    Patro.postUrl = @"index.php/FoodCheckApi/ledgerOutNewAdd.json";
    Patro.supplierId = supplierId;
    Patro.ishidenSearch = NO;
    Patro.Reqmodel = list;
    Patro.isEdit= NO;
    Patro.isdeleMore=NO;
    Patro.isGroupStyle=YES;
    Patro.searchName=@"请输入商品名称";
    Patro.title= @"新增出货";
    Patro.is_Out = YES;
    Patro.on_operation = isEdit;
    [self.navigationController pushViewController:Patro animated:YES];
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}


-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/ledgerOutList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        CandLModel *InforModel=[CandLModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"台账"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=TBNODateType;
                
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                self.btn.hidden=NO;
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
